<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">
        <!-- 搜索 -->
        <el-form size="mini" :model="numberValidateForm" ref="numberValidateForm" class="demo-ruleForm">
          <div class="userserch">
            <el-form-item prop="username">
              <el-input placeholder="根据用户名搜索" v-model="numberValidateForm.username"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="clear('numberValidateForm')">清空</el-button>
              <el-button type="primary" @click="sousou('numberValidateForm')">搜索</el-button>
            </el-form-item>
          </div>
          <!-- 点击触发父组件add自定义事件 -->
          <el-button type="success" size="small" @click="centerDialogVisible = true"><i class="el-icon-edit"></i>新增权限组</el-button>
        </el-form>
        <el-alert type="info" show-icon :closable="false">
          <span slot="title">共{{ counts }}条数据</span>
        </el-alert>
        <!-- 表格 -->
        <el-table :default-sort="{ prop: 'date', order: 'descending' }" highlight-current-row :data="list" style="width: 100%">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column align="center" prop="title" label="组别" width="522"> </el-table-column>
          <el-table-column prop="create_date" sortable label="日期" width="521">
            <template slot-scope="scope">
              <span>{{ scope.row.create_date | Sewer }} </span>
            </template>
          </el-table-column>
          <el-table-column align="right" label="操作" width="150">
            <template slot-scope="scope" class="caozuo">
              <!-- 再把接收的数据发给编辑组件，这里的scope可以拿到当前这行的数据 -->
              <el-button type="primary" plain icon="el-icon-edit" circle @click=";[onEdit(scope), (centerDialogVisible = true)]"></el-button>
              <el-button type="danger" plain icon="el-icon-delete" circle @click="open(scope)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pages.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pages.pagesize"
          layout="prev,pager, next,sizes, jumper"
          :total="counts"
        >
        </el-pagination>
        <!-- 权限管理弹窗-->
        <el-dialog title="创建权限组" :visible="centerDialogVisible" @close="resetForm" width="50%" center>
          <div class="up">
            <el-form :model="qxname" ref="qxname" label-width="100px" class="demo-ruleForm">
              <el-form-item label="用户名" prop="name" :rules="[{ required: true, message: '用户名称不能为空' }]">
                <el-input v-model="qxname.name"></el-input>
              </el-form-item>
            </el-form>
            <!-- 树形的控件 -->
            <el-tree ref="tree" :props="defaultProps" node-key="id" :default-expanded-keys="[1]" :default-checked-keys="permissions" :data="treedata" show-checkbox> </el-tree>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="resetForm()">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<style lang="scss" scoped>
</style>

<script>
// 获取树形结构
import { list as treenode } from '@/api/base/menus.js'
// 获取，删除,详情,添加,修改
import { list, remove, detail, add, update } from '@/api/base/permissions'
export default {
  created () {
    this.getList()
    // 树形
    this.gettreenode()
  },
  name: 'base-permissions',
  data () {
    return {
      updataid: '', // 获取的编辑id
      // 树节点自定义属性
      defaultProps: {
        children: 'childs',
        label: 'title'
      },
      // 默认选中
      permissions: [],
      // 用户名
      // 树形控件
      treedata: [
        {
          id: 1,
          title: '系统菜单和页面权限点',
          childs: []
        }
      ],
      qxname: {
        name: '' // 权限组输入框
      },
      centerDialogVisible: false, // 弹出层控制按钮
      // 输入框双向绑定
      numberValidateForm: {
        username: ''
      },
      pages: {
        page: 1,
        pagesize: 10
      },
      counts: 0,
      list: []
    }
  },
  methods: {
    // 搜索
    async sousou () {
      const res = await list({ page: this.pages.page, pagesize: this.pages.pagesize, title: this.numberValidateForm.username })
      console.log(res)
      this.list = res.data.list
    },
    // 分页器
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pages.pagesize = val
      // 发请求刷新
      this.getList()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.getList()
    },
    // 弹出层确定按钮
    async onEdit (val) {
      // 发送当前页id
      const res = await detail(val.row)
      this.updataid = val.row.id
      this.qxname.name = res.data.title
      this.permissions = res.data.permissions
      // console.log(res.data)
      console.log('获取详情成功')
      // 点击的时候获取这个传回的数据并传过去
    },
    // 发送请求获取表格数据
    async getList () {
      const { data } = await list(this.pages)
      // console.log(data)
      this.counts = data.counts
      this.list = await data.list
    },
    // 发送树形结构获取请求
    async gettreenode () {
      const { data } = await treenode()
      // console.log(data)
      this.treedata[0].childs = data
    },
    // 确定按钮
    submitForm () {
      this.$refs.qxname.validate(async (valid) => {
        if (valid) {
          // 先判断是不是添加按钮,如果获取的长度为0,为添加按钮
          if (this.permissions.length === 0) {
            console.log('添加')
            // 获取当前的节点数据
            const res = this.$refs.tree.getCheckedNodes()
            res.forEach((itme) => {
              this.permissions.push(itme.id)
            })
            // console.log(this.permissions)
            // 发送添加请求
            await add({ title: this.qxname.name, permissions: this.permissions })
            // 刷新页面
            this.getList()
          } else {
            this.permissions.length = 0
            console.log('编辑')
            // 发送编辑请求
            const res = this.$refs.tree.getCheckedNodes()
            // console.log(res)
            res.forEach((itme) => {
              this.permissions.push(itme.id)
            })
            // console.log(this.permissions)
            // 发送修改请求
            await update({ id: this.updataid, title: this.qxname.name, permissions: this.permissions })
            // 刷新页面
            this.getList()
          }
        } else {
          console.log('error submit!!')
          return false
        }
        // 无论如何
        // 关闭弹窗
        this.centerDialogVisible = false
        // 清空树形
        this.$refs.tree.setCheckedKeys([])
        // 清空树形的选中变量
        this.permissions.length = 0
      })
    },
    resetForm () {
      // 清空输入框
      this.$refs.qxname.resetFields()
      // 关闭弹窗
      this.centerDialogVisible = false
      // 清空树形
      this.$refs.tree.setCheckedKeys([])
      this.permissions.length = 0
    },
    clear (numberValidateForm) {
      // 清空输入框
      this.$refs[numberValidateForm].resetFields()
      console.log('为什么不清空?')
      this.getList()
    },
    // 删除按钮
    // 点击按钮告诉主页面要删除的id
    open (val) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 给用户一个确定是否要删除的弹窗
          console.log(val.row.id)
          console.log('获取删除id成功')
          // 触发删除请求
          await remove(val.row)
          // 刷新页面
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .box-card {
  width: 100%;
  .el-card__header {
    border-bottom: none;
  }
  .el-alert {
    margin-top: 20px;
  }
  .el-card__body {
    position: relative;
    padding: 0 20px;
  }
}
::v-deep .pages {
  float: right;
}
.demo-ruleForm {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  .el-input__inner {
    width: 256px;
  }
  .userserch {
    width: 330px;
    display: flex;
    justify-content: space-between;
  }
  .el-form-item {
    margin-bottom: 0;
  }
}
::v-deep .up {
  width: 50%;
  margin: 0 auto;
}
::v-deep .el-pagination {
  float: right;
}
</style>
